package com.zzg.test2.manager

import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import android.webkit.WebResourceResponse
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.InputStream
import java.net.URL
import java.util.concurrent.ConcurrentHashMap
import kotlin.math.log

@SuppressLint("StaticFieldLeak") object CacheManager {
    val TAG = "CacheManager"
    private val memoryCache = ConcurrentHashMap<String, WebResourceResponse>()
    private lateinit var context: Context

    fun init(context: Context) {
        this.context = context.applicationContext
    }

    fun get(url: String): WebResourceResponse? {
        // 先从内存缓存中查找
        memoryCache[url]?.let { return it }

        // 再从磁盘缓存中查找
        val cacheFile = getCacheFile(url)
        if (cacheFile.exists()) {
            try {
                Log.d(TAG, "从磁盘缓存中获取资源 cacheFile = $cacheFile")
                val inputStream = FileInputStream(cacheFile)
                val mimeType = getMimeType(url)
                val response = WebResourceResponse(mimeType, "UTF-8", inputStream)
                memoryCache[url] = response
                return response
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return null
    }

    fun put(url: String, inputStream: InputStream) {
        try {
            val cacheFile = getCacheFile(url)
            val outputStream = FileOutputStream(cacheFile)
            inputStream.use { input ->
                outputStream.use { output ->
                    input.copyTo(output)
                }
            }

            val mimeType = getMimeType(url)
            val response = WebResourceResponse(mimeType, "UTF-8", FileInputStream(cacheFile))
            memoryCache[url] = response
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

     fun getCacheFile(url: String): File {
        val cacheDir = context.getExternalFilesDir(null)
        val fileName = url.hashCode().toString()
        return File(cacheDir, fileName)
    }

     fun getMimeType(url: String): String {
        return when {
//            url.endsWith(".html", true) || url.endsWith(".htm", true) -> "text/html"
            url.endsWith(".css", true) -> "text/css"
            url.endsWith(".js", true) -> "application/javascript"
            url.endsWith(".png", true) -> "image/png"
            url.endsWith(".jpg", true) || url.endsWith(".jpeg", true) -> "image/jpeg"
            url.endsWith(".gif", true) -> "image/gif"
            url.endsWith(".svg", true) -> "image/svg+xml"
            url.endsWith(".ico", true) -> "image/x-icon"
            url.endsWith(".woff", true) -> "font/woff"
            url.endsWith(".woff2", true) -> "font/woff2"
            else -> "text/html"
        }
    }
}